<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>促销活动管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button
          type="danger"
          icon="delete"
          class="handle-del mr10"
          @click="deleteAllHandler"
          >批量删除</el-button
        >
        <el-input
          placeholder="请输入关键字"
          class="handle-input mr10"
          v-model="searchInfo"
        ></el-input>
        <el-button type="primary" icon="search" @click="searchSale"
          >搜索</el-button
        >
        <el-button type="primary" @click="addSaleVisible = true"
          >添加活动</el-button
        >
        <el-button type="primary" @click="handlerDownloadALL"
          >导出全部</el-button
        >
      </div>
      <el-table
        border
        class="table"
        :data="sale"
        @selection-change="handleSelectionChange"
        v-loading="isShowloading"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="sale_id"
          label="序号"
          sortable
          width="150"
        ></el-table-column>
        <el-table-column
          prop="sale_name"
          label="活动名称"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="sale_info"
          label="活动内容"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="sale_inTime"
          label="活动开始时间"
        ></el-table-column>
        <el-table-column
          prop="sale_outTime"
          label="活动结束时间"
        ></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :page-sizes="[3, 5, 10, 20, 50]"
          :current-page="currentPage"
          @current-change="currentChange"
          @size-change="sizeChangeHandler"
        >
        </el-pagination>
      </div>
      <!-- 编辑框 -->
      <el-dialog
        title="修改信息"
        :visible.sync="editSaleVisible"
        ref="editSaleForm"
        v-dialogDrag
      >
        <el-form ref="editSaleForm" :model="saleForm">
          <el-form-item
            label="编号"
            :label-width="formLabelWidth"
            prop="sale_id"
            hidden
          >
            <el-input v-model="saleForm.sale_id" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="活动名称"
            :label-width="formLabelWidth"
            prop="sale_name"
          >
            <el-input
              v-model="saleForm.sale_name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="活动内容"
            :label-width="formLabelWidth"
            prop="sale_info"
          >
            <el-input
              v-model="saleForm.sale_info"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="活动开始时间"
            :label-width="formLabelWidth"
            prop="sale_inTime"
          >
            <el-col :span="11">
              <el-date-picker
                v-model="saleForm.sale_inTime"
                type="date"
                placeholder="选择日期"
                style="width: 100%;"
              ></el-date-picker>
            </el-col>
            <el-col class="line" :span="2" style="text-align: center">-</el-col>
            <el-col :span="11">
              <el-time-picker
                v-model="saleForm.sale_inTime"
                placeholder="选择时间"
                style="width: 100%;"
              ></el-time-picker>
            </el-col>
          </el-form-item>
          <el-form-item
            label="活动结束时间"
            :label-width="formLabelWidth"
            prop="sale_outTime"
          >
            <el-col :span="11">
              <el-date-picker
                v-model="saleForm.sale_outTime"
                type="date"
                placeholder="选择日期"
                style="width: 100%;"
              ></el-date-picker>
            </el-col>
            <el-col class="line" :span="2" style="text-align: center">-</el-col>
            <el-col :span="11">
              <el-time-picker
                v-model="saleForm.sale_outTime"
                placeholder="选择时间"
                style="width: 100%;"
              ></el-time-picker>
            </el-col>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editSaleVisible = false">取 消</el-button>
          <el-button type="primary" @click.native="editSaleHanlder"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <!-- 添加 -->
      <el-dialog
        title="添加信息"
        :visible.sync="addSaleVisible"
        ref="addSaleForm"
        v-dialogDrag
      >
        <el-form :model="addSaleForm">
          <el-form-item
            label="编号"
            :label-width="formLabelWidth"
            prop="sale_id"
            hidden
          >
            <el-input
              v-model="addSaleForm.sale_id"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="活动名称"
            :label-width="formLabelWidth"
            prop="sale_name"
          >
            <el-input
              v-model="addSaleForm.sale_name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="活动内容"
            :label-width="formLabelWidth"
            prop="sale_info"
          >
            <el-input
              v-model="addSaleForm.sale_info"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="活动开始时间"
            :label-width="formLabelWidth"
            prop="sale_inTime"
          >
            <el-col :span="11">
              <el-date-picker
                v-model="addSaleForm.sale_inTime"
                type="date"
                placeholder="选择日期"
                style="width: 100%;"
              ></el-date-picker>
            </el-col>
            <el-col class="line" :span="2" style="text-align: center">-</el-col>
            <el-col :span="11">
              <el-time-picker
                v-model="addSaleForm.sale_inTime"
                placeholder="选择时间"
                style="width: 100%;"
              ></el-time-picker>
            </el-col>
          </el-form-item>
          <el-form-item
            label="活动结束时间"
            :label-width="formLabelWidth"
            prop="sale_outTime"
          >
            <el-col :span="11">
              <el-date-picker
                v-model="addSaleForm.sale_outTime"
                type="date"
                placeholder="选择日期"
                style="width: 100%;"
              ></el-date-picker>
            </el-col>
            <el-col class="line" :span="2" style="text-align: center">-</el-col>
            <el-col :span="11">
              <el-time-picker
                v-model="addSaleForm.sale_outTime"
                placeholder="选择时间"
                style="width: 100%;"
              ></el-time-picker>
            </el-col>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addSaleVisible = false">取 消</el-button>
          <el-button type="primary" @click="addSaleHandler">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
/* global Xlsx:false */ //解决老是报为定义错的方式
import { getSaleList, updateSale, addSale, deleteSale } from "../../../api/api";
export default {
  data() {
    return {
      sale: [],
      delSale: [],
      editSaleVisible: false,
      saleForm: {},
      searchInfo: "",
      addSaleForm: {
        sale_name: "",
        sale_info: "",
        sale_inTime: "",
        sale_outTime: ""
      },
      pageSize: 3,
      datetime: "",
      formLabelWidth: "120px",
      addSaleVisible: false,
      total: 0,
      currentPage: 1,
      isShowloading: false
    };
  },
  mounted() {
    this.getSale();
  },
  methods: {
    handlerDownloadALL() {
      const tableData = [
        ["活动编号", "活动名称", "活动内容", "活动开始时间", "活动结束时间"]
      ];
      this.sale.forEach(item => {
        const rowData = [
          item.sale_id,
          item.sale_name,
          item.sale_info,
          item.sale_inTime,
          item.sale_outTime
        ];
        tableData.push(rowData);
      });
      const ws = Xlsx.utils.aoa_to_sheet(tableData);
      const wb = Xlsx.utils.book_new();
      const date = new Date();
      Xlsx.utils.book_append_sheet(wb, ws, "活动数据"); // 工作簿名称
      Xlsx.writeFile(wb, `活动数据${date.toLocaleString()}.xlsx`); // 保存的文件名
    },
    handleSelectionChange(delSale) {
      this.delSale = delSale;
    },
    getSale() {
      let pageNo = this.currentPage;
      this.isShowloading = true;
      const start = pageNo * 10;
      getSaleList().then(result => {
        this.sale = result.slice((pageNo - 1) * 10, start);
        this.total = result.length;
        this.isShowloading = false;
      });
    },
    currentChange(val) {
      this.currentPage = val;
      this.getSale();
    },
    sizeChangeHandler(size) {
      this.pageSize = size;
    },
    searchSale() {
      let search = this.searchInfo;
      if (this.searchInfo.length === 0) {
        this.getSale();
      }
      if (search) {
        this.sale = this.sale.filter(item => {
          return Object.keys(item).some(key => {
            return String(item[key]).indexOf(search) > -1;
          });
        });
      }
    },
    deleteAllHandler() {
      this.$confirm("确认批量删除吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          let delIds = this.delSale.map(item => item.sale_id);
          for (let i = 0; i < delIds.length; i++) {
            deleteSale(this.delSale[i]).then(result => {
              if (result) {
                this.sale = this.sale.filter(item => {
                  if (item.sale_id !== delIds[i]) {
                    return item;
                  }
                });
              }
            });
          }
          this.$message({
            type: "success",
            message: "删除成功！"
          });
        })
        .catch(() => {
          console.log("cancel");
        });
    },
    handleEdit(index, row) {
      this.editSaleVisible = true;
      this.saleForm = Object.assign({}, row);
    },
    handleDelete(index, row) {
      this.$confirm("确认删除该活动？", "提示", {
        type: "warning"
      })
        .then(() => {
          deleteSale(row).then(result => {
            if (result) {
              this.sale = this.sale.filter(item => {
                if (item.sale_id !== row.sale_id) {
                  return item;
                }
              });
              this.$message({
                type: "success",
                message: "删除成功！"
              });
            }
          });
        })
        .catch(() => {
          console.log("取消删除");
        });
    },
    addSaleHandler() {
      if (!this.addSaleForm) return;
      let params = Object.assign({ sale_id: this.total + 1 }, this.addSaleForm);
      addSale(params).then(result => {
        if (result) {
          this.$message({
            type: "success",
            message: "添加成功！"
          });
          params.sale_inTime = this.changeTime(params.sale_inTime);
          params.sale_outTime = this.changeTime(params.sale_outTime);
          this.sale = [params, ...this.sale];
          this.addSaleVisible = false;
        }
      });
    },
    changeTime(date) {
      return (
        date.getFullYear() +
        "-" +
        (date.getMonth() + 1) +
        "-" +
        date.getDate() +
        " " +
        date.getHours() +
        ":" +
        date.getMinutes() +
        ":" +
        date.getSeconds()
      );
    },
    editSaleHanlder() {
      this.$refs["editSaleForm"].validate(valid => {
        if (valid) {
          let data = this.saleForm;
          updateSale(data)
            .then(result => {
              if (result) {
                this.$message({
                  type: "success",
                  message: "修改成功！"
                });
                if (typeof data.sale_inTime === "object") {
                  data.sale_inTime = this.changeTime(data.sale_inTime);
                }
                if (typeof data.sale_outTime === "object") {
                  data.sale_outTime = this.changeTime(data.sale_outTime);
                }
                this.sale = this.sale.map(item => {
                  if (item.sale_id === data.sale_id) {
                    return {
                      ...item,
                      ...data
                    };
                  }
                  return item;
                });
                this.editSaleVisible = false;
                this.saleForm = {};
              }
            })
            .catch(e => console.log(e));
        }
      });
    }
  }
};
</script>
<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
</style>
